package com.hengyue.system.repository;

import com.hengyue.common.core.respository.BaseRepository;
import com.hengyue.system.domain.entity.SysRole;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

@Repository
public interface SysRoleRepository extends BaseRepository<SysRole, Long> {

    @Query("select distinct menu.perms from SysRole r join r.menus menu where r.id in :roleIds")
    List<String> findPermsByRoleId(@Param("roleIds") Set<Long> roleIds);

    @Query("SELECT DISTINCT r FROM SysRole r JOIN r.users u WHERE u.id = :userId order by r.roleSort asc")
    List<SysRole> findRoleKeysByUserId(@Param("userId") Long userId);

    /**
     * 根据用户 ID 获取用户未授权的角色集
     * @param userId 用户 ID
     * @return 用户未授权的角色集
     */
    @Query("SELECT r FROM SysRole r WHERE r NOT IN (SELECT DISTINCT u.sysRoles FROM SysUser u WHERE u.id = :userId)")
    List<SysRole> findUnassignedRolesByUserId(Long userId);

    /**
     * 批量删除角色与用户的关联关系
     * @param roleId 角色 ID
     * @param userIds 用户 ID 数组
     * @return 删除的记录数
     */
    @Modifying
    @Query(value = "DELETE FROM user_role WHERE role_id = ?1 AND user_id IN ?2", nativeQuery = true)
    void deleteUserRoleRelations(Long roleId, Long[] userIds);


    boolean existsByCodeAndIdNot(String roleCode, Long excludeRoleId);

    boolean existsByNameAndIdNot(String roleName, Long excludeRoleId);

    boolean existsByRoleKeyAndIdNot(String roleKey, Long excludeRoleId);

}